package com.funny.wallpaper

import android.annotation.SuppressLint
import android.app.WallpaperManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.graphics.drawable.BitmapDrawable
import android.media.ThumbnailUtils
import android.os.Build
import android.view.WindowManager
import androidx.annotation.DimenRes
import com.`fun`.funlivewallpaper.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object FunnyWallpaperHelper {
    private var defaultWallpaperBg: Bitmap? = null
    private var wallpaperPreviewBg: Bitmap? = null
    private var wallpaperHongbaoBg: Bitmap? = null
    var screenWidth = 0
    var screenHeight = 0
    var wallpaperHongBaoWidth = 0
    var wallpaperHongBaoHeight = 0
    var hasSetInWallpaper = false
    fun init(context: Context) {
        initScreen(context)
        hasSetInWallpaper = hasSetInWallpaper(context)
        wallpaperHongBaoWidth = screenWidth - getDimensionPixelSize(context, R.dimen.dp_60)
        wallpaperHongBaoHeight = (wallpaperHongBaoWidth * (110 / 316f)).toInt()

        if (!hasSetInWallpaper) {
            CoroutineScope(Dispatchers.IO).launch {
                try {// 缓存当前的壁纸
                    val wallpaperManager0 = context.getSystemService(android.content.Context.WALLPAPER_SERVICE) as WallpaperManager
                    @SuppressLint("MissingPermission")
                    val drawable0 = wallpaperManager0.drawable
                    defaultWallpaperBg = ThumbnailUtils.extractThumbnail(
                        (drawable0 as BitmapDrawable).bitmap,
                        screenWidth, screenHeight
                    )
                    val editPicDir = File(context.filesDir, "wall")
                    editPicDir.mkdirs()
                    val wrapperFile = File(editPicDir.absolutePath + "/wall.jpeg")
                    wrapperFile.deleteOnExit()
                    try {
                        wrapperFile.createNewFile()
                        val outStream = FileOutputStream(wrapperFile)
                        defaultWallpaperBg!!.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
                        outStream.flush()
                        outStream.close()
                        saveUserDefaultWallpaperPath(context, wrapperFile.absolutePath)
                    } catch (var6: IOException) {
                        var6.printStackTrace()
                    }
                } catch (e: Throwable) {

                }
            }
        }
    }

    fun getDimensionPixelSize(context: Context, @DimenRes v: Int): Int {
        return context.resources.getDimensionPixelSize(v)
    }

    private fun initScreen(context: Context) {
        val windowManager0: WindowManager =
            context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point0 = Point()
        if (Build.VERSION.SDK_INT >= 17) {
            windowManager0.getDefaultDisplay().getRealSize(point0)
        } else {
            windowManager0.getDefaultDisplay().getSize(point0)
        }
        screenHeight = point0.y
        screenWidth = point0.x
    }

    fun getDefaultWallpaperBg(context: Context): Bitmap? {
        if (defaultWallpaperBg == null) {
            try {
                val userDefaultWallpaperPath = getUserDefaultWallpaperPath(context)
                if (!userDefaultWallpaperPath.isNullOrEmpty()) {
                    val file = File(userDefaultWallpaperPath)
                    if (file.exists()) {
                        defaultWallpaperBg = BitmapFactory.decodeFile(file.getAbsolutePath());
                    }
                }
            } catch (e: Exception) {
            }
            if (defaultWallpaperBg == null) {
                defaultWallpaperBg = ThumbnailUtils.extractThumbnail(
                    BitmapFactory.decodeResource(
                        context.resources,
                        R.drawable.default_wallpaper
                    ), screenWidth, screenHeight
                )
            }
        }
        return defaultWallpaperBg
    }

    fun getWallpaperPreviewBg(context: Context): Bitmap? {
        if (wallpaperPreviewBg == null) {
            wallpaperPreviewBg = ThumbnailUtils.extractThumbnail(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.drawable.wallpaper_preview_bg
                ), screenWidth, screenHeight
            )
        }
        return wallpaperPreviewBg
    }

    fun getWallpaperHongbaoBg(context: Context): Bitmap? {
        if (wallpaperHongbaoBg == null) {
            wallpaperHongbaoBg = ThumbnailUtils.extractThumbnail(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.drawable.wallpaper_hongbao
                ), wallpaperHongBaoWidth, wallpaperHongBaoHeight
            )
        }
        return wallpaperHongbaoBg
    }

    fun hasSetInWallpaper(context: Context): Boolean {
        return try {
            val mWallpaperManager: WallpaperManager = WallpaperManager.getInstance(context)
            mWallpaperManager.getWallpaperInfo().getPackageName() == context.packageName
        } catch (e: Exception) {
            false
        }
    }

    fun setToWallPaper(context: Context) {
//        try {
////            WallpaperManager.getInstance(context)
////                .clear()
//        } catch (e: IOException) {
//        }
        try {
            val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
            intent.putExtra(
                WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                ComponentName(context, FunnyWallpaperService::class.java)
            )
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun saveUserDefaultWallpaperPath(context: Context, str: String) {
        if (str.isNotEmpty()) {
            val sp = context.getSharedPreferences("dwp", Context.MODE_PRIVATE)
            sp.edit().putString("d", str).apply()
        }
    }

    private fun getUserDefaultWallpaperPath(context: Context): String? {
        val sp = context.getSharedPreferences("dwp", Context.MODE_PRIVATE)
        return sp.getString("d", "")
    }


}
